package addressBook;

import lombok.Data;

/**
 * @author Jarvan
 * @version 1.0
 * @create 2020/11/13 8:52
 */
@Data
public class AddressBook implements ADTAddressBook{

    /** binary search tree */
    private BinarySearchTree<Contact> tree;


    /** count of contacts */

    private int count;

    /**
     * No args constructor.
     */
    public AddressBook() {
        tree = new BinarySearchTree<>();
        count = 0;
    }

    /**
     * insert a new contact into this address book,
     *
     * @param contact contact
     */
    @Override
    public boolean insertContact(Contact contact) {
        boolean flag = tree.insertItem(contact);
        if (flag) {
            count ++;
        }
        return flag;
    }

    /**
     * delete a contact from this address book,
     *
     * @param contactName contactName
     */
    @Override
    public boolean deleteContact(String contactName) {
        boolean flag = tree.remove(new Contact(contactName,null,null));
        if (flag) {
            count --;
        }
        return flag;
    }

    /**
     * search a contact in this address book,
     *
     * @param contactName contactName
     */
    @Override
    public Contact searchContact(String contactName) {
        Contact result = null;
        try {
            result = tree.searchItem(new Contact(contactName, null, null)).element;
        } catch (NullPointerException e) {
            System.err.println("====search fail haven't this element =====");
        }
        return  result;
    }

    /**
     * get a reference to a contact from this address book,
     */
    @Override
    public Contact getReference() {
        return tree.root.element;
    }

    /**
     * check how many contacts are there in this address book,
     */
    @Override
    public int length() {
        return count;
    }

    /**
     * check to see if the address book is empty
     */
    @Override
    public boolean isEmpty() {
        return count<=0;
    }

    /**
     * • and completely empty this address book.
     */
    @Override
    public boolean removeAllContacts() {
        tree.root = null;
        count = 0;
        return true;
    }
}
